<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品id" prop="spActiveId">
        <el-input
          v-model="queryParams.spActiveId"
          placeholder="请输入商品id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库id" prop="spHouseId">
        <el-input
          v-model="queryParams.spHouseId"
          placeholder="请输入仓库id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库存数量" prop="quantity">
        <el-input
          v-model="queryParams.quantity"
          placeholder="请输入库存数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:record:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:record:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:record:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:record:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="combinedList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="库存id" align="center" prop="id" />
      <el-table-column label="订单id" align="center" prop="spOrderSn" />
      <el-table-column label="订单时间" align="center" prop="createTime" />
      <el-table-column label="仓库" align="center" prop="houseName" />
      <el-table-column label="商品名称" align="center" prop="spActiveName" />
      <el-table-column label="规格名称" align="center" prop="spNormsName" />
      <el-table-column label="数量" align="center" prop="quantity" width="100px"/>
      <el-table-column label="出入库状态" align="center" prop="status" width="180px">
        <template slot-scope="scope">
          <dict-tag v-if="scope.row.sellOrPurchaseStatus !== null" :options="dict.type.shop_purchase_sell_status" :value="scope.row.status" />
          <span v-else>——</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:record:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  listRecord,
  getRecord,
  delRecord,
  addRecord,
  updateRecord,
  selectPurchaseSell,
  getRecordDetails, getRecordBySell
} from '@/api/shop/record'
import { getHouse } from '@/api/shop/house'

export default {
  name: "Record",
  dicts:['shop_purchase_sell_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //库存列表
      recordList:[],
      sellList:[],//出库列表
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        spActiveId: null,
        spHouseId: null,
        quantity: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      sellOrPurchaseStatus:'',
      formStatusData:[],
      combinedList:[]
    };
  },
  created() {
    this.getList();
    this.getStatus();
  },

  methods: {
    /** 查询库存管理列表 */
  /*   getList() {
      this.loading = true;
      listRecord(this.queryParams).then(res=>{
        console.log(res.rows)
        this.recordList = res.rows.map(record=>({
          ...record,
          houseName : null
        }))

        Promise.all(this.recordList.map(record=>{
          return getHouse(record.spHouseId).then(houseRes=>{
            record.houseName = houseRes.data.houseName
          })
        })).then(()=>{
          this.total = res.total;
          console.log('120--------------------------',this.recordList)
          this.loading = false;
        }).catch(error=>{
          console.log(error)
          this.loading = false
        })

      }).catch(error=>{
        console.log(error)
        this.loading = false
      })
    }, */
    getList(){
      this.loading = true;
      const promisePurchase =getRecordDetails().then(res=>{
        console.log(res.rows)
        this.recordList = res.rows.map(record=>({
          ...record,
          houseName : null
        }))

        Promise.all(this.recordList.map(record=>{
          return getHouse(record.spHouseId).then(houseRes=>{
            record.houseName = houseRes.data.houseName
          })
        })).then(()=>{
          this.total = res.rows.length;
          console.log('120--------------------------',this.recordList)
          this.loading = false;
        }).catch(error=>{
          console.log(error)
          this.loading = false
        })
      }).catch(error=>{
        console.log(error)
        this.loading = false
      })

    //   --------------------------------------------
      const promiseSell = getRecordBySell().then(res=>{
        console.log("出库...........",res.rows)
        this.sellList = res.rows.map(record=>({
          ...record,
          houseName : null
        }))

        Promise.all(this.sellList.map(record=>{
          return getHouse(record.spHouseId).then(houseRes=>{
            record.houseName = houseRes.data.houseName
          })
        })).then(()=>{
          this.total = res.rows.length;
          console.log('150--------------------------',this.sellList)
          this.loading = false;
        }).catch(error=>{
          console.log(error)
          this.loading = false
        })
      }).catch(error=>{
        console.log(error)
        this.loading = false
      })

      // 使用Promise.all等待两个Promise都完成
      Promise.all([promisePurchase, promiseSell]).then(() => {
        // 在这里，两个数组（recordList 和 sellList）都已经填充了houseName
        // 合并这两个数组
        this.combinedList = [...this.recordList, ...this.sellList];
        this.total = this.combinedList.length;
        console.log('Combined List:', this.combinedList);
        this.loading = false;
      }).catch(error => {
        console.log(error);
        this.loading = false;
      });
    },


    getStatus(){
      selectPurchaseSell().then(res=>{
        console.log('出入状态.............',res)
        this.formStatusData = res.data
        console.log(this.formStatusData)

        if (this.formStatusData.purchaseStatus === null || this.formStatusData.purchaseStatus === '') {
          this.sellOrPurchaseStatus = this.formStatusData.sellStatus || 'null';
        } else {
          this.sellOrPurchaseStatus = this.formStatusData.purchaseStatus;
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        spActiveId: null,
        spHouseId: null,
        quantity: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加库存管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRecord(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改库存管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除库存管理编号为"' + ids + '"的数据项？').then(function() {
        return delRecord(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/record/export', {
        ...this.queryParams
      }, `record_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
